package com.itheima.servlet;


import com.alibaba.fastjson.JSON;
import com.itheima.bean.User;
import com.itheima.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/ChargeServlet")
public class ChargeServlet extends HttpServlet {

    private final UserService userService = new UserService();

    @Override//这个get方法可以得到当前登录的对象  但是为了保证安全这个对象的密码为空
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/plain;charset=utf-8");
        //从会话域中取出用户对象
        User user = (User) req.getSession().getAttribute("user");
        String jsonString = JSON.toJSONString(user);
        System.out.println(jsonString);
        //发送
        resp.getWriter().println(jsonString);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String addMoney = req.getParameter("addMoney");
        double money = Double.parseDouble(addMoney);
        User user = (User) req.getSession().getAttribute("user");
        Double newMoney = user.getMoney() + money;
        userService.changeMoney(user.getId(), newMoney);
        //修改会话区里面用户的值
        user.setMoney(newMoney);
        req.getSession().setAttribute("user",user);
        //充钱完毕跳回充值页面
        resp.sendRedirect("add-money.html");
    }
}
